package com.neu.questionnaireplus.service.impl;

import cn.hutool.core.lang.Filter;
import cn.hutool.dfa.StopChar;
import cn.hutool.dfa.WordTree;
import com.neu.questionnaireplus.service.ForbiddenVocabularyCheckService;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class ForbiddenVocabularyCheckServiceImpl implements ForbiddenVocabularyCheckService {

  @Override
  public List<String> checkStrs(String str) {
    try {
      WordTree tree = uploadV();
      Filter<Character> charFilter = StopChar::isNotStopChar;
      tree.setCharFilter(charFilter);
      List<String> list = tree.matchAll(str, -1, false, false);
      return list;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public boolean isForbidden(String str) {
    try {
      WordTree tree = uploadV();
      Filter<Character> charFilter = StopChar::isNotStopChar;
      tree.setCharFilter(charFilter);
      return tree.isMatch(str);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  /**
  * @Description: 装载敏感词，生成检测字典树 ,不能在service层使用全局变量，会出现线程安全问题，
   * 网上说的在controller层利用注解和Model设置全局变量的本质也是每次接受请求结束后重新加载全局变量，和手动加载性能无太多差异
  * @Param: []
  * @return: cn.hutool.dfa.WordTree
  * @Author: ~FHX~ (:TSunS:)
  * @Date: 2022/11/8
  */
  private WordTree uploadV() throws IOException {
    //可以用数据库读，但再建一个数据库有点麻烦，作为测试就直接写在本地一个文件下了，不同的敏感词用中文；隔开
    File file = new File("C:\\Users\\fuck rog\\Desktop\\V.txt");
    FileReader reader = new FileReader(file);
    BufferedReader bReader = new BufferedReader(reader);
    StringBuilder sb = new StringBuilder();
    String s = "";
    while ((s =bReader.readLine()) != null) {
      sb.append(s + "\n");
    }
    bReader.close();
    String str = sb.toString();
    String[] split = str.split("；");
    List<String> list = new ArrayList<>(Arrays.asList(split));
    WordTree tree = new WordTree();
    for (String s1 : list){
      tree.addWord(s1);
    }
    return tree;
  }
}
